<template>
  <div :class="fileList.length >= limit ? 'hideupload' : ''">
    <el-upload
      action="http://47.107.118.26:15000/admin/v2/api/upload/productFile"
      :headers="{
        Authorization: `Bearer ${$store.state.user.token}`
      }"
      list-type="picture-card"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :file-list="fileList"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'Upload',

  props: {
    // eslint-disable-next-line vue/require-default-prop
    defaultUrl: [String, Array],

    // 最大上传个数限制
    limit: {
      type: Number,
      default: 1
    }
  },

  data() {
    return {
      imageUrl: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },

  computed: {
    fileList() {
      const { defaultUrl } = this
      let arr = []
      // 传过来的是数组
      if (Array.isArray(defaultUrl)) {
        for (let i = 0; i < defaultUrl.length; i++) {
          arr.push({
            url: defaultUrl[i]
          })
        }
      } else if (defaultUrl) {
        // 传过来的是字符串
        arr.push({
          url: defaultUrl
        })
      }

      return arr
    }
  },

  methods: {
    // 上传成功
    handleAvatarSuccess(res) {
      const { code, data, msg } = res
      if (code === 0) {
        this.$emit('upload', data.url)
      } else {
        this.$message.warning(msg)
      }
    },

    // 上传前
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },

    // 预览
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    // 删除
    handleRemove(file) {
      this.$emit('remove', file.url)
    }
  }
}
</script>

<style lang="scss">
.hideupload {
  .el-upload {
    display: none;
  }
}
</style>
